package com.csair.demo.basedao;

import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.csair.demo.utils.ReflectionUtils;

/**
 * <b>function:</b> 运用SqlSessionDaoSupport封装Dao常用增删改方法，可以进行扩展
 * @author hoojo
 * @createDate 2011-4-13 下午06:33:37
 * @file BaseDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@Repository
public abstract class MybatisEntityDao<T> extends SqlSessionDaoSupport implements IMybatisEntityDao<T> {
	
	/**
	 * DAO实体代理的Entity类型.
	 */
	protected Class<T> entityClass;

	/**
	 * 在构造函数中将泛型T.class赋给entityClass.
	 */
	public MybatisEntityDao() {
		this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass(),0);
	}

	/**
	 * 取得entityClass.JDK1.4不支持泛型的子类可以抛开Class<T> entityClass,重载此函数达到相同效果�?
	 */
	protected Class<T> getEntityClass() {
		return entityClass;
	}

	
	@Autowired
	private SqlSessionFactory sqlSessionFactory;
	
	public boolean add(String classMethod, T entity) throws Exception {
		boolean flag = false;
		try {
			flag = this.getSqlSession().insert(classMethod, entity) > 0 ? true : false;
		} catch (Exception e) {
			flag = false;
			throw e;
		}
		return flag;
	}

	public boolean edit(String classMethod, T entity) throws Exception {
		boolean flag = false;
		try {
			flag = this.getSqlSession().update(classMethod, entity) > 0 ? true : false;
		} catch (Exception e) {
			flag = false;
			throw e;
		}
		return flag;
	}

	public T get(String classMethod, Long id) throws Exception {
		T result = null;
		try {
			result = (T) this.getSqlSession().selectOne(classMethod, id);
		} catch (Exception e) {
			throw e;
		}
		return result;
	}

	public List<T> getAll(String classMethod) throws Exception {
		List<T> result = new ArrayList<T>();
		try {
			result = this.getSqlSession().selectList(classMethod);
		} catch (Exception e) {
			throw e;
		}
		return result;
	}

	public boolean remove(String classMethod, Long id) throws Exception {
		boolean flag = false;
		try {
			flag = this.getSqlSession().delete(classMethod, id) > 0 ? true : false;
		} catch (Exception e) {
			flag = false;
			throw e;
		}
		return flag;
	}

	public PageFinder findPage(PageWhere pageTag) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
